<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParmas.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTreeRef"
          :data="treeData"
          :props="treeProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          @node-click="handlerNodeClick"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push(`/employee/detail`)">添加员工</el-button>
          <el-button size="mini" @click="import2Excel">excel导入</el-button>
          <el-button size="mini" @click="export2Excel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table border stripe :data="userList">
          <el-table-column prop="staffPhoto" label="头像" align="center">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" size="medium" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" align="center" />
          <el-table-column prop="mobile" label="手机号" align="center" />
          <el-table-column prop="workNumber" label="工号" align="center" />
          <el-table-column prop="formOfEmployment" label="聘用形式" align="center" :formatter="formatterFromOf" />
          <!-- <template #default="{ row }">
              <span>{{ row.formOfEmployment == 1 ? '正式' : '未正式' }}</span>
            </template> -->
          <!-- </el-table-column> -->
          <el-table-column prop="departmentName" label="部门" align="center" />
          <el-table-column prop="timeOfEntry" label="入职时间" align="center" />
          <el-table-column label="操作" align="center" width="140px">
            <template #default="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="ShowAssignRole(row.id)">角色</el-button>
              <template>
                <el-popconfirm
                  title="确认删除该行数据吗？"
                  @onConfirm="delEmployee(row.id)"
                >
                  <el-button slot="reference" size="mini" type="text" style="margin-left: 10px;">删除</el-button>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :current-page="queryParmas.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="queryParmas.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <importExcel :show-excel-dialog.sync="showExcelDialog" @update-list="loadUserList" />
      <!-- 员工角色页面 -->
      <AssignRole :id="id" :is-show-assign-role.sync="isShowAssignRole" />
    </div>
  </div>
</template>

<script>
import AssignRole from './components/assign-role.vue'
import { formOfEmloyment as EnumformofEmployment } from './constant/formofEmployment'
import { getCompanyDepartment } from '@/api/department/department'
import { listTree } from '@/utils'
import { delSysUser, getUser, getUserExport } from '@/api/employee/employee'
import { saveAs } from 'file-saver'
import _ from 'lodash' // 推荐取 _ 作为 它的引用名称
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: { importExcel, AssignRole },
  data() {
    return {
      treeData: [],
      treeProps: {
        label: 'name',
        children: 'children'
      },
      queryParmas: {
        // 存储查询参数
        departmentId: null,
        page: 1,
        pagesize: 5,
        keyword: ''
      },
      total: 0,
      userList: [],
      debounceHanlder: null,
      showExcelDialog: false,
      isShowAssignRole: false,
      // 角色功能id
      id: null
    }
  },
  watch: {
    'queryParmas.keyword': {
      handler(newWord) {
        this.debounceHanlder(newWord)
      }
    }
  },
  mounted() {
    this.loadTreeData()

    // 先去处理一个具有防抖功能的函数
    this.debounceHanlder = _.debounce((newWord) => {
      this.queryParmas.page = 1
      this.queryParmas.keyword = newWord
      this.loadUserList()
    }, 500)
  },
  methods: {
    async loadTreeData() {
      const res = await getCompanyDepartment()
      this.treeData = listTree(res, 0)
      // 记录当前所有部门中第一个部门的id
      this.queryParmas.departmentId = res[0].id

      // vue内部:数据更新是异步的
      // 如果想获取到数据的最新状态的话,就要等整个数据更新流程完毕之后
      this.$nextTick(() => {
        // 这里的回调会在下一次dom更新完毕之后执行
        this.$refs.deptTreeRef.setCurrentKey(this.queryParmas.departmentId)

        // 获取列表数据
        this.loadUserList()
      })
    },
    // 更新存储查询参数
    async handlerNodeClick(dept) {
      this.queryParmas.departmentId = dept.id
      await this.loadUserList()
    },
    // 获取-员工列表
    async loadUserList() {
      const { rows, total } = await getUser(this.queryParmas)
      // 接收列表数据、总数
      this.userList = rows
      this.total = total
    },
    handleSizeChange(pagesize) {
      this.queryParmas.pagesize = pagesize
      this.loadUserList()
    },
    async handleCurrentChange(page) {
      this.queryParmas.page = page
      // const { rows, total } = await getUser(this.queryParmas)
      // this.userList = rows
      // this.total = total
      this.loadUserList()
    },
    // 用来格式化聘用形式的
    formatterFromOf(row) {
      const current = EnumformofEmployment.find(item => item.value === row.formOfEmployment)
      // console.log(current)
      return current?.text ?? '未知'
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await delSysUser(id)
        this.$message.success('删除员工成功')
        this.loadUserList()
      } catch (error) {
        console.log(error)
      }
    },
    // async findEmployee() {
    //   const res = await getUser(this.queryParmas)
    //   this.userList = res.rows
    // },
    // 导出excel
    async export2Excel() {
      const res = await getUserExport()
      saveAs(res, '员工信息表.xlsx')
    },
    // 导入excel
    import2Excel() {
      this.showExcelDialog = true
    },
    // 显示员工角色功能页面
    ShowAssignRole(id) {
      this.isShowAssignRole = true
      this.id = id
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
